package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户Controller
 *
 * @author ruoyi
 * @date 2020-04-20
 */
@Controller
@RequestMapping("/system/customer")
public class WorkCustomerController extends BaseController {
    private String prefix = "system/customer";

    @Value("${newUrl}")
    private String newUrl;

    @Autowired
    private IWorkCustomerService workCustomerService;

    @Autowired
    private IWorkFormService iWorkFormService;

    @Autowired
    private IWorkFaultService iWorkFaultService;
    @Autowired
    private IWorkPhotoService iWorkPhotoService;
    @Autowired
    private ISysUserService iSysUserService;

    //@RequiresPermissions("system:customer:view")
    @GetMapping()
    public String customer() {
        return prefix + "/customer";
    }

    /**
     * 查询用户列表
     */
    // @RequiresPermissions("system:customer:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkCustomer workCustomer) {
        startPage();
        List<WorkCustomer> list = workCustomerService.selectWorkCustomerList(workCustomer);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    // @RequiresPermissions("system:customer:export")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WorkCustomer workCustomer) {
        List<WorkCustomer> list = workCustomerService.selectWorkCustomerList(workCustomer);
        ExcelUtil<WorkCustomer> util = new ExcelUtil<WorkCustomer>(WorkCustomer.class);
        return util.exportExcel(list, "customer");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增工单
     */
    @GetMapping("/workForm/{id}")
    public String workForm(@PathVariable String id, ModelMap model) {
        model.addAttribute("id", id);
        String loginName = ShiroUtils.getLoginName();
        Long userId = ShiroUtils.getUserId();
        model.addAttribute("loginName",loginName);
        model.addAttribute("userId",userId);
        return prefix + "/custadd";
    }

    /**
     * 新增保存用户
     */
    //@RequiresPermissions("system:customer:add")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WorkCustomer workCustomer) {
        workCustomer.setStatus("1");
        return toAjax(workCustomerService.insertWorkCustomer(workCustomer));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        WorkCustomer workCustomer = workCustomerService.selectWorkCustomerById(id);
        mmap.put("workCustomer", workCustomer);
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    //@RequiresPermissions("system:customer:edit")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WorkCustomer workCustomer) {
        return toAjax(workCustomerService.updateWorkCustomer(workCustomer));
    }

    /**
     * 删除用户
     */
    // @RequiresPermissions("system:customer:remove")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(workCustomerService.deleteWorkCustomerByIds(ids));
    }

    //@RequiresPermissions("system:customer:workForm")
    @Log(title = "用户", businessType = BusinessType.transfer)
    @RequestMapping("/uploadTo")
    @ResponseBody
    public AjaxResult test(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();

        int index = fileName.lastIndexOf(".");
        if(index<0){
            return toAjax(false);
        }
        String suffixName = fileName.substring(index);
        List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
        if (!extList.contains(suffixName)) {
            return toAjax(false);
        }

        fileName = UUID.randomUUID().toString().replace("-", "") + System.currentTimeMillis() + suffixName;
        //String url = "localhost:9004"+s + fileName;
        File dest = new File(newUrl + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return toAjax(true);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 新增工单
     */
    //@RequiresPermissions("system:customer:edit")
    @Log(title = "新增工单", businessType = BusinessType.UPDATE)
    @PostMapping("/addFrom")
    @ResponseBody
    public AjaxResult addForm(@RequestParam("file") MultipartFile[] file, Long userId, String description, Long custId) {
        Map<String, String> map = new HashMap<>();
        for (MultipartFile multipartFile : file) {
            String fileName = multipartFile.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            if(index<0){
                return toAjax(false);
            }
            String suffixName = fileName.substring(index);
            List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
            if (!extList.contains(suffixName)) {
                return toAjax(false);
            }
            fileName = UUID.randomUUID().toString().replace("-", "") + System.currentTimeMillis() + suffixName;
            String url = "localhost:9004" + fileName;
            map.put(fileName, url);
            File dest = new File(newUrl + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                throw new RuntimeException();
            }
        }

        WorkForm workForm = new WorkForm();
        workForm.setCreateTime(DateUtils.getNowDate());
        workForm.setCheckStatus("0");
        SysUser sysUser = iSysUserService.selectUserById(userId);
        workForm.setCreateUser(sysUser.getLoginName());
        workForm.setHoldUser(sysUser.getLoginName());
        workForm.setReturnStatus("0");
        workForm.setWorkStatus("0");
        workForm.setTransferStatus("0");

        iWorkFormService.insertWorkForm(workForm);
        WorkFault workFault = new WorkFault();
        workFault.setCustId(custId);
        workFault.setDescription(description);
        workFault.setFormId(workForm.getId());
        iWorkFaultService.insertWorkFault(workFault);
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            WorkPhoto workPhoto = new WorkPhoto();
            workPhoto.setPhotoName(entry.getKey());
            workPhoto.setPhotoUrl(entry.getValue());
            iWorkPhotoService.insertWorkPhoto(workPhoto);
            iWorkPhotoService.insertWorkPhotoByFault(workFault.getId(), workPhoto.getId());
        }

        return toAjax(1);

    }
}
